/*----------------------------MegaWave2 module----------------------------*/
/* mwcommand
name = {cmthre};
version = {"1.0"};
author = {"Baptiste Coulange"};
function = {"Thresholding (egal of fthre but for fmovies)"};
usage = {
 'n'->norm    "to normalize pixel values from actual to [min,max]",
 'N'->N       "to normalize pixel values from actual or [min,max] to [0,255]",
 'm':min->min "specify minimal pixel value (min)",
 'M':max->max "specify maximal pixel value (max)",
 'p':p->p[0,100] "to discard a ratio of p percent pixels with minimal values",
 'q':q->q[0,100] "to discard a ratio of q percent pixels with maximal values",
 'd':d->d[0,100] "to discard a ratio of d percent pixels with extremal values",
 'a'->aff     "to prevent thresholding (affine normalization only)",
 'l'->linear  "force linear normalization (preserve 0)",
 in->in       "input Fimage", 
 out<-out     "output thresholded/renormalized Fimage"
};
*/
/*----------------------------------------------------------------------
v1.0 (04/2007): initial version
----------------------------------------------------------------------*/

#include <stdio.h>
#include <math.h>
#include "mw.h"


float fimmin(in)
	Fimage in;
{
	float resu;
	int adr;
	float w;

	resu=(float)in->gray[in->nrow*in->ncol];
			
	for (adr=in->nrow*in->ncol-1;adr--;) {
      w = in->gray[adr];
		if (w<resu) resu=w;
	    }

return(resu);
}

float fimmax(in)
	Fimage in;
{
	float max;
	int adr;
	float w;
	max;

	max=(float)in->gray[in->nrow*in->ncol];
		
	for (adr=in->nrow*in->ncol-1;adr--;) {
      w = in->gray[adr];
		if (w>max) max=w;
	    }
	return(max);
}

Fimage cmthre(in,out,norm,N,min,max,p,q,d,aff,linear)
   Fmovie in,out;
   char    *norm,*N,*aff,*linear;
   float   *min,*max,*p,*q,*d;

{
	out=mw_change_fmovie(out);
	Fimage prec,oprec,anc;
	prec=in->first;
	float m0u,m1u,m0Loc,m1Loc;
	
	m1u=fimmax(prec);
	m0u=fimmin(prec);
	if(min){
		m0u=*min;
		if(max){
		m1u=*max;
		} else {
		m1Loc=fimmax(prec);
			while(prec->next){
				prec=prec->next;
				m1Loc=fimmax(prec);
				if (m1Loc>m1u) m1u=m1Loc;
			}
		}
	} else {
		if(max) {m1u=*max;
		} else {
		m0u=fimmin(prec);
		m1u=fimmax(prec);	
			while(prec->next){
				prec=prec->next;
				m0Loc=fimmin(prec);
				m1Loc=fimmax(prec);
				if (m0u>m0Loc) m0u=m0Loc;
				if (m1Loc>m1u) m1u=m1Loc;
			}
		}	
	}
	
	
	prec=in->first;
	oprec=mw_change_fimage(NULL,prec->nrow,prec->ncol);
	out->first=oprec;
	fthre(prec,oprec,norm,N,&m0u,&m1u,p,q,d,aff,linear);
	anc=oprec;
	while(prec->next){
	prec=prec->next;
	oprec=mw_change_fimage(NULL,prec->nrow,prec->ncol);	
	fthre(prec,oprec,norm,N,&m0u,&m1u,p,q,d,aff,linear);
	anc->next=oprec;
	oprec->previous=anc;
	anc=oprec;
	}
}


